﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Amba.KeyValueStorage.Extensions
{
    internal static class ObjectExtensions
    {
        public static T IfNotNull<T>(this T obj, Action<T> action)
        {
            if (obj == null)
                return obj;
            action(obj);
            return obj;
        }

        public static IEnumerable<T> Dequeue<T>(this Queue<T> queue, int count)
        {
            var result = new List<T>();
            for (int i = 0; i < count; i++)
            {
                if (queue.Any())
                    result.Add(queue.Dequeue());
            }
            return result;
        }

        public static void ProcessListBySlice<T>(this IEnumerable<T> list, int batchSize, Action<IEnumerable<T>> action)
        {
            var queue = new Queue<T>(list);
            for (int i = 0; i < Math.Ceiling((double)queue.Count / batchSize); i++)
            {
                if (!queue.Any())
                    return;
                action(queue.Dequeue(batchSize));
            }
        }
    }
}